using Abc.Core.Entities;

using Furion.DatabaseAccessor;
using Furion.DependencyInjection;

using Mapster;

using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

using Tool;

namespace Abc.Application
{
    /// <summary>
    /// 通知
    /// </summary>
    [ApiDescriptionSettings(Name = "Notice")]
    //[Injection(Proxy = typeof(LogDispatchProxy))]
    [ServiceFilter(typeof(ApiActionFilterAttribute))]
    public class NoticeService : INoticeService, ITransient
    {
        private readonly ILogger<NoticeService> _logger;
        private readonly IRepository<Notice> _noticeRepository;

        //private readonly IMemoryCache _memoryCache;
        public NoticeService(ILogger<NoticeService> logger
        //, IMemoryCache memoryCache
        , IRepository<Notice> noticeRepository
         )
        {
            _logger = logger;
            // _memoryCache = memoryCache;
            //_memoryCache =  App.GetService<IMemoryCache>();
            _noticeRepository = noticeRepository;
        }

        /// <summary>
        /// 新增或更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> InsertOrUpdate(NoticeInput input)
        {
            var resultdata = new ResultData<string>();
            if (input.Id > 0)
            {
                var dbentity = await _noticeRepository.FindAsync(input.Id);
                input.Adapt(dbentity);
                await _noticeRepository.UpdateAsync(dbentity);
            }
            else
            {
                var newEntity = await _noticeRepository.InsertAsync(input.Adapt<Notice>());
            }
            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        /// <summary>
        /// 删除一条
        /// </summary>
        /// <param name="id"></param>
        public async Task<ResultData<string>> Delete(int id)
        {
            var resultdata = new ResultData<string>();
            await _noticeRepository.DeleteAsync(id);

            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        /// <summary>
        /// 查询一条[跟踪实体]
        /// </summary>
        /// <param name="id"></param>
        public async Task<NoticeOut> Find(int id)
        {
            var dbentity = await _noticeRepository.FindAsync(id);
            return dbentity.Adapt<NoticeOut>();
        }

        /// <summary>
        /// 查询一条[跟踪实体]
        /// </summary>
        /// <param name="id"></param>
        public async Task<NoticeOut> Get(int id)
        {
            var dbentity = await _noticeRepository.FirstOrDefaultAsync(o => o.Id == id, tracking: false);
            if (dbentity == null) return null;
            return dbentity.Adapt<NoticeOut>();
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        public async Task<PagedListToLayui<NoticeOut>> GetAllByPageToLayui(NoticeQuery searchQuery)
        {
            //var queryable= _noticeRepository.DetachedEntities.AsQueryable();
            //if (!string.IsNullOrWhiteSpace(searchQuery.KeyWords))
            //{
            //    var kw = searchQuery.KeyWords.ToLower();
            //    queryable = queryable.Where(o => o.No.Contains(kw));
            //}

            var pageResult = _noticeRepository.DetachedEntities.AsQueryable().OrderByDescending(o => o.Id).ProjectToType<NoticeOut>();
            return await pageResult.ToPagedListToLayuiAsync(searchQuery.Page, searchQuery.Limit);
        }

        #region 默认未启用

        /// <summary>
        /// 新增一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> Insert(NoticeInput input)
        {
            var resultdata = new ResultData<string>();
            var newEntity = await _noticeRepository.InsertAsync(input.Adapt<Notice>());

            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        /// <summary>
        /// 更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> Update(int id, NoticeInput input)
        {
            var resultdata = new ResultData<string>();
            var dbentity = await _noticeRepository.FindAsync(id);
            input.Adapt(dbentity);
            await _noticeRepository.UpdateAsync(dbentity);

            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        /// <summary>
        /// 新增或更新多条
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> Inserts(List<NoticeInput> inputs)
        {
            var resultdata = new ResultData<string>();
            var dbaddinputs = inputs.Adapt<List<Notice>>();
            await _noticeRepository.InsertAsync(dbaddinputs);
            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        /// <summary>
        /// 新增或更新多条
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> Updates(List<NoticeInput> inputs)
        {
            var resultdata = new ResultData<string>();
            var ids = inputs.Select(o => o.Id).ToList();
            var dbentitys = await _noticeRepository.Where(u => ids.Any(a => a == u.Id)).ToListAsync();
            inputs.Adapt(dbentitys);
            await _noticeRepository.UpdateAsync(dbentitys);

            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        /// <summary>
        /// 新增或更新多条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<ResultData<string>> InsertOrUpdates(List<NoticeInput> inputs)
        {
            var resultdata = new ResultData<string>();
            if (inputs.Any(o => o.Id > 0))
            {
                var updates = inputs.Where(o => o.Id > 0);
                var ids = updates.Select(o => o.Id).ToList();
                var dbentity = _noticeRepository.Where(o => ids.Any(a => a == o.Id));
                inputs.Adapt(dbentity);
                await _noticeRepository.UpdateAsync(dbentity);
            }
            else
            {
                var adds = inputs.Where(o => o.Id <= 0);
                await _noticeRepository.InsertAsync(adds.Adapt<List<Notice>>());
            }
            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        /// <summary>
        /// 查询所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<NoticeOut>> GetAll()
        {
            var entities = _noticeRepository.DetachedEntities.AsQueryable().ProjectToType<NoticeOut>();
            var datas = await entities.ToListAsync();
            datas.SetMemoryCache("Table_Notice");
            return datas;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        public async Task<PagedList<NoticeOut>> GetAllByPage(NoticeQuery searchQuery)
        {
            //var queryable= _noticeRepository.DetachedEntities.AsQueryable(tracking:false);
            //if (!string.IsNullOrWhiteSpace(searchQuery.KeyWords))
            //{
            //    var kw = searchQuery.KeyWords.ToLower();
            //    queryable = queryable.Where(o => o.No.Contains(kw));
            //}
            var pageResult = _noticeRepository.DetachedEntities.AsQueryable().OrderByDescending(o => o.Id).ProjectToType<NoticeOut>();

            return await pageResult.ToPagedListAsync(searchQuery.Page, searchQuery.Limit);
        }

        /// <summary>
        /// 设置状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="state"></param>
        /// <param name="field">字段名</param>
        /// <returns></returns>
        public async Task<ResultData<string>> SetState(int id, bool state, string field)
        {
            var resultdata = new ResultData<string>();
            var entity = await _noticeRepository.FirstOrDefaultAsync(o => o.Id == id);

            switch (field.ToLower())
            {
                case "isread":
                    {
                        entity.IsRead = state;
                    }
                    break;

                default:
                    break;
            }

            resultdata.Succeeded = true;
            resultdata.Errors = "操作成功";
            return resultdata;
        }

        #endregion 默认未启用
    }

    public interface INoticeService
    {
        /// <summary>
        /// 新增或更新一条
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        Task<ResultData<string>> InsertOrUpdate(NoticeInput input);

        /// <summary>
        /// 删除一条
        /// </summary>
        /// <param name="id"></param>
        Task<ResultData<string>> Delete(int id);

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="id"></param>
        Task<NoticeOut> Find(int id);

        /// <summary>
        /// 查询一条
        /// </summary>
        /// <param name="id"></param>
        Task<NoticeOut> Get(int id);

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="searchQuery"></param>
        /// <returns></returns>
        Task<PagedListToLayui<NoticeOut>> GetAllByPageToLayui(NoticeQuery searchQuery);

        #region 默认未启用

        ///// <summary>
        ///// 新增一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Insert(NoticeInput input);
        //
        ///// <summary>
        ///// 更新一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Update(int id,NoticeInput input);
        ///// <summary>
        ///// 新增或更新一条
        ///// </summary>
        ///// <param name="input"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Inserts(List<NoticeInput> inputs);
        ///// <summary>
        ///// 新增或更新多条
        ///// </summary>
        ///// <param name="inputs"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> Updates(List<NoticeInput> inputs);
        ///// <summary>
        ///// 新增或更新多条
        ///// </summary>
        ///// <param name="inputs"></param>
        ///// <returns></returns>
        //Task<ResultData<string>> InsertOrUpdates(List<NoticeInput> inputs);
        ///// <summary>
        ///// 查询所有
        ///// </summary>
        ///// <returns></returns>
        //Task<List<NoticeOut>> GetAll();
        ///// <summary>
        ///// 分页查询
        ///// </summary>
        ///// <param name="searchQuery"></param>
        ///// <returns></returns>
        //Task<PagedList<NoticeOut>> GetAllByPage(NoticeQuery searchQuery);
        ///// <summary>
        ///// 设置状态
        ///// </summary>
        ///// <param name="id"></param>
        ///// <param name="state"></param>
        ///// <param name="field">字段名</param>
        ///// <returns></returns>
        //Task<ResultData<string>> SetState(int id, bool state, string field);

        #endregion 默认未启用
    }
}